﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace Utilities
{
    [XmlRoot("users")]
    public class UserList
    {
        ArrayList _lstUsers;

        public UserList()
        {
            _lstUsers = new ArrayList();
        }

        [XmlElement("user")]
        public User[] Users
        {
            get
            {
                User[] lst = new User[_lstUsers.Count];
                _lstUsers.CopyTo(lst);
                return lst;
            }
            set
            {
                if (value == null) return;
                User[] lst = (User[])value;
                _lstUsers.Clear();
                foreach (User u in lst)
                    _lstUsers.Add(u);
            }
        }

        //add new user to user list
        public int AddUser(User u)
        {
            foreach (User user in this.Users)
            {
                if (u.Email.Equals(user.Email))
                {
                    throw new Exception("người dùng đã tồn tại trong cơ sở dữ liệu.");
                }
            }
            return _lstUsers.Add(u);
        }


        //checking user when sign in with email and password
        public bool CheckUser(string email, string pass)
        {
            foreach (User user in this.Users)
            {
                if (email.Equals(user.Email))
                {
                    // check passphrase

                    byte[] salt = Utility.FromHexStringToBytes(user.Salt);
                    byte[] inputBytes = Encoding.ASCII.GetBytes(pass);

                    TripleDESCryptoServiceProvider tripleDesCsp = new TripleDESCryptoServiceProvider();

                    // Create password
                    PasswordDeriveBytes pdb = new PasswordDeriveBytes(inputBytes, salt);
                    byte[] passByteDerived = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, tripleDesCsp.IV);

                    byte[] inputHashBytes = EncryptionProvider.Hash(passByteDerived, new SHA1Managed());
                    string inputHash = Utility.FromBytesToHexString(inputHashBytes);

                    return (inputHash.Equals(user.PassHash));
                }
            }
            return false;
        }

        //update user
        public void UpdateUserAt(int pos, User user)
        {
            _lstUsers[pos] = user;
        }

        //get user by email
        public User GetUserByEmail(string email)
        {
            foreach (User user in this.Users)
            {
                if (email.Equals(user.Email))
                {
                    return user;
                }
            }
            return null;
        }
    }
}
